public class Solution98 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isValidBST(TreeNode root) {
        return valid(root)[0]==1;
    }

    public int[] valid(TreeNode root){
        int[] ans=new int[3];
        if (root.left!=null){
            int[] t=valid(root.left);
            if (t[0]==0 || t[2]>=root.val || root.left.val>=root.val){
                return new int[]{0,0,0};
            }
            ans[1]=t[1];
        }else{
            ans[1]=root.val;
        }
        if (root.right!=null){
            int[] t=valid(root.right);
            if (t[0]==0 || t[1]<=root.val || root.right.val<=root.val){
                return new int[]{0,0,0};
            }
            ans[2]=t[2];
        }else{
            ans[2]=root.val;
        }
        ans[0]=1;
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution98().isValidBST(new TreeNode(5,new TreeNode(1),new TreeNode(4,new TreeNode(3),new TreeNode(6)))));
    }


}
